package com.twan.kotlinbase.factory;

import android.content.Context;
import android.content.Intent;
import android.view.View;

import com.blankj.utilcode.util.SPUtils;
import com.google.gson.JsonParseException;
import com.twan.kotlinbase.bean.ApiException;
import com.twan.kotlinbase.ui.LoginActivity;
import com.twan.kotlinbase.util.UIUtils;
import com.twan.kotlinbase.widgets.AlertDialog;
import com.twan.kotlinbase.widgets.CustomProgress;

import org.json.JSONException;
import java.io.IOException;
import java.net.ConnectException;

import retrofit2.adapter.rxjava.HttpException;

/**
 * Created by paopao on 2018/7/13.
 */

public class ApiErrorHelper {
    static AlertDialog alertDialog;
    public static void handleCommonError(Context context, Throwable e) {
        CustomProgress.setdismiss();
        if (e instanceof HttpException) {
//            UIUtils.showToast("网络错误");
        } else if (e instanceof IOException) {
//            UIUtils.showToast("连接失败");
        }else if(e instanceof JsonParseException
                || e instanceof JSONException){
//            UIUtils.showToast("解析错误");
        }else if(e instanceof ConnectException){
//            UIUtils.showToast("端口连接失败");
        } else
        if (e instanceof ApiException) {
            //ApiException处理
            ApiException exception= (ApiException) e;
            if((exception.getmErrorCode() == 405)){
                SPUtils.getInstance().clear();
                if(alertDialog!=null&&alertDialog.isShowimg()){
                    alertDialog.setDismiss();
                    alertDialog=null;
                }
                alertDialog=new AlertDialog(context);
                alertDialog.builder().setCancelable(false)
                        .setTitle("提示").setMsg(exception.getMessage())
                        .setNegativeButton("取消", new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {

                            }
                        })
                        .setPositiveButton("确定", new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                Intent intent=new Intent(context, LoginActivity.class);
                                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                context.startActivity(intent);
                            }
                        }).show();
            }else{
                UIUtils.showToast(e.getMessage());
            }
        } else {
//            UIUtils.showToast("连接错误");
        }
    }

}
